import 'dart:async';
import 'dart:convert';
import 'dart:io';

import 'package:dio/adapter.dart';
import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:hygf/http/file_transfer/upload_result.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:package_info/package_info.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';

import '../../config/ApiConfig.dart';
import '../../util/LoadingUtils.dart';
import '../../view/dialog/dialog_manager.dart';
import '../../view/image_picker_widget.dart';
import '../DioClient.dart';
import '../core/ResponseData.dart';
import 'VersionStatus.dart';

/// [DioClient]扩展
/// 为[DioClient]添加下载能力
extension DownCAP on DioClient {
  /// todo
  /// 根据对象存储地址获取预览url
  ///
  getFilesPreviewUrls() {}

  Future<ResponseData> getFilePreviewUrl(String objectStoragePath) async {
    // ResponseData downRes = await doGet("${ApiConfig.objectStorageUrl}/minio/presigned_download_url",
    //     queryParameters: {
    //       "objectName": objectStoragePath,
    //     },
    //     options: Options(extra: {"hideLoading": true}));

    ResponseData res = ResponseData.fromJson({"data": ""});
    res.isok = true;
    res.code = "1";
    res.data = getPreviewUrlSync(objectStoragePath);
    return res;
  }

  String getPreviewUrlSync(String objectStoragePath) {
    return "${ApiConfig.mainUrl}/file/service/minio/preview_file?objectName=$objectStoragePath&hayden=${ApiConfig.getToken}";
  }

  Future<VersionStatus> checkVersion(BuildContext context, bool hideLoading,
      {bool autoUpload = false}) async {
    if (Platform.isIOS) {
      return VersionStatus.current;
    }
    if (!hideLoading) {
      LoadingUtils.loading();
    }
    var packageInfo = await PackageInfo.fromPlatform();
    int currentVersion = int.parse(packageInfo.version.replaceAll(".", ""));

    Map<String, dynamic> data = {
      "_api_key": "ffbb294d91021c0d3b2628918e8a5f80",
      "appKey": "277fad68a41e37136d5d636f4ae8a73c",
    };
    ResponseData response = await DioClient().doPost("https://www.pgyer.com/apiv2/app/check",
        queryParameters:data,options: Options(extra: {"hideLoading": true}));
    if (!hideLoading) {
      LoadingUtils.dismiss();
    }
    if (response.isok) {
      Map<String, dynamic> data = response.data;
      if(data["buildVersion"] !=null){
        String downloadUrl = data["downloadURL"] ?? "";
        int minVersion =
        int.parse((data["buildVersion"] as String).replaceAll(".", ""));
        if (currentVersion < minVersion) {
          DialogManager.showUpdateDialog(context,
              url: downloadUrl, force: true, autoUpload: autoUpload,version:data["buildVersion"]);
          return VersionStatus.force;
        } else {
          // 不需要更新
          return VersionStatus.current;
        }
      }else{
        return VersionStatus.current;
      }
    } else {
      LoadingUtils.showError("获取版本更新失败");
      return VersionStatus.netError;
    }
  }

  /// 下载
  ///
  /// [url] 下载地址
  /// [path] 存储位置
  /// [onProgress] 进度监听方法 参数为进度 0～1
  /// [cancelToken] 取消下载的token
  ///
  /// 返回值为是否成功
  ///
  Future<bool> down({
    required String url,
    required String path,
    required Function(double) onProgress,
    CancelToken? cancelToken,
  }) async {
    var dio = Dio();
    // 跳过https ssl证书校验
    (dio.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate =
        (client) {
      client.badCertificateCallback = (cert, host, port) {
        return true;
      };
    };
    try {
      var responst =
          await dio.download(url, path, onReceiveProgress: (received, total) {
        if (total == -1) {
          onProgress(0.0);
        } else {
          onProgress(received / total);
        }
      }, cancelToken: cancelToken);
      if (kDebugMode) {
        print(responst);
      }

      if (responst.statusCode == 200) {
        return true;
      } else {
        return false;
      }
    } on Exception {
      return false;
    }
  }

  /// 下载图片
  downloadImage(String url) async {
    if (await Permission.storage.request().isGranted) {
      LoadingUtils.loading(status: '下载中');
      var response = await Dio().get(url, options: Options(responseType: ResponseType.bytes));
      final result = await ImageGallerySaver.saveImage(Uint8List.fromList(response.data));
      LoadingUtils.dismiss();
      if (result["isSuccess"] ?? false) {
        LoadingUtils.showToast("下载成功");
      } else {
        LoadingUtils.showToast("下载失败");
      }
    }else{
      LoadingUtils.showToast("未获取存储权限");
    }
  }


  Future<List<ImagePickerData>> requestImgUrl(String? idList,{List? tempList}) async {
    List<ImagePickerData> data = [];
    List<String> parts = [];
    if(tempList!=null){
      parts = tempList.map((e) => e.toString()).toList();
    }else{
      parts = idList!.split(',');
    }
    for (var item in parts) {
      int itemId = int.parse(item);
      UploadResult uploadResult = await requestImgData(itemId);
      if((uploadResult.url??"").isNotEmpty){
        data.add(ImagePickerData(uploadResult.fileName??"", uploadResult.url??"",id:itemId));
      }
    }
    return data;
  }

   Future<UploadResult> requestImgData(int id) async {
    var url = "${ApiConfig.uploadFile}/$id";
    ResponseData responseData = await DioClient().doPost(url,
        options: Options(
            extra: {"hideLoading": true},
            headers: {"content-type": "application/x-www-form-urlencoded"}));
    if(responseData.code == "0"){
      UploadResult entity = UploadResult.fromJson(responseData.data);
      return entity;
    }else{
      return UploadResult();
    }
  }
}
